//
//  HomeTableView.m
//  Custom_Weibo
//
//  Created by LEO on 12/11/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "HomeTableView.h"
#import "HomeCell.h"
#import "DetailViewController.h"

@implementation HomeTableView

#pragma mark - INITIALIZATION_METHODS
- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        
        //  If you also has a custom cell created by nib, you should register.
        UINib *nib = [UINib nibWithNibName:@"HomeCell" bundle:nil];
        [self registerNib:nib forCellReuseIdentifier:kCellID];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        
        UINib *nib = [UINib nibWithNibName:@"HomeCell" bundle:nil];
        [self registerNib:nib forCellReuseIdentifier:kCellID];
    }
    return self;
}

#pragma mark - TABLE_VIEW_DATASOURCE_AND_DELEGATE
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*  The height depends on the weibo detail view height and the original 
     cell's frame.
     */
    WeiboViewLayoutFrame *layoutFrame = self.dataArray[indexPath.row];
    return layoutFrame.mainFrame.size.height + 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID
                                                     forIndexPath:indexPath];
    cell.layoutFrame = _dataArray[indexPath.row];
    return cell;
}

#pragma mark - DETAIL_VIEW
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detailView = [[DetailViewController alloc] init];
    detailView.title = @"Detail Page";
    detailView.layoutFrame = _dataArray[indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.belongingController.navigationController pushViewController:detailView
                                                             animated:YES];
}

@end
